﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SSMS_Scripter
{
    public partial class GroupByDialog : Form
    {
        public List<int> GroupColumns { get; set; }
        public GroupByDialog(TableMenuItem parent, string connectionString, string dbName, string tableName, string schemaName)
        {
            menuParent = parent;
            SchemaName = schemaName;
            TableName = tableName;
            DbName = dbName;
            ConnectionString = connectionString;
            InitializeComponent();

            GroupColumns = new List<int>();

            PopulateColumnList();
        }

        private void PopulateColumnList()
        {
            dgvColumns.DataSource = GetColumnList();
        }
        private DataTable GetColumnList()
        {
            string query = "USE {0}\n" +
                        "select column_name [ColumnName] from information_schema.columns\n" +
                        "where table_name = '{1}' AND TABLE_SCHEMA = '{2}' order by ordinal_position";

            query = string.Format(query, DbName, TableName, SchemaName);

            SqlConnection conn = new SqlConnection(ConnectionString);
            SqlCommand comm = new SqlCommand(query, conn);
            SqlDataAdapter sda = new SqlDataAdapter(comm);
            DataSet ds = new DataSet();
            
            sda.Fill(ds);

            return ds.Tables[0];
        }

        private void HandleGroupByToggle(DataGridViewCellEventArgs e, DataGridView dgv)
        {
            DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgvColumns.Rows[e.RowIndex].Cells[e.ColumnIndex];

            if((bool)checkCell.Value)
            {
                GroupColumns.Add(e.RowIndex);
                SetOrder(e.RowIndex);
            }
            else
            {
                int listIndex = GroupColumns.IndexOf(e.RowIndex);
                GroupColumns.RemoveAt(listIndex);
                SetOrder(e.RowIndex, "");

                for (int i = listIndex; i < GroupColumns.Count; i++)
                {
                    SetOrder(GroupColumns[i], i + 1);
                }
            }
        }

        private void SetOrder(int rowIndex)
        {
            int count = GroupColumns.Count;
            SetOrder(rowIndex, count);
        }

        private void SetOrder(int rowIndex, int val)
        {
            SetOrder(rowIndex, val.ToString());
        }

        private void SetOrder(int rowIndex, string val)
        {
            dgvColumns.Rows[rowIndex].Cells[dgvColumns.Columns.IndexOf(dgvColumns.Columns["Order"])].Value = val;
        }

        public string ConnectionString { get; private set; }
        public string DbName { get; private set; }
        public string TableName { get; private set; }
        public string SchemaName { get; private set; }
        public TableMenuItem menuParent { get; private set; }

        private void dgvColumns_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvColumns.IsCurrentCellDirty)
            {
                dgvColumns.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void dgvColumns_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvColumns.Columns[e.ColumnIndex].Name.Equals("GroupBy"))
            {
                HandleGroupByToggle(e, dgvColumns);

                dgvColumns.Invalidate();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            List<string> result = new List<string>();
            for (int i = 0; i < GroupColumns.Count; i++)
            {
                result.Add((string)dgvColumns.Rows[GroupColumns[i]].Cells[dgvColumns.Columns.IndexOf(dgvColumns.Columns["ColumnName"])].Value);
            }

            menuParent.StoreGroupBy(result);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
